package cn.cai.handler;

import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义登录成功后的处理器
 * 转发或者重定向，由代码逻辑实现
 */
public class MyAuthenticationSucessHandler implements AuthenticationSuccessHandler {
    private String url;
    private boolean isRedirect;

    public MyAuthenticationSucessHandler(String url, boolean isRedirect) {
        this.url = url;
        this.isRedirect = isRedirect;
    }

    /**
     *
     * @param httpServletRequest 请求对象。request.getRequestDispatcher().forward()
     * @param httpServletResponse 响应对象。response.sendRedirect();
     * @param authentication 用户认证（登录）成功后的对象。其中包含用户名和权限集合。内容是
     *                       自定义的UserDetailsService 实现的方法值对象提供的。
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        System.out.println("自定义认证处理逻辑执行.........");

        if(isRedirect){
            httpServletResponse.sendRedirect(url);
        }else {
            httpServletRequest.getRequestDispatcher(url).forward(httpServletRequest,httpServletResponse);
        }
    }

    // getXxx()、setXxx()

    public String getUrl() {
        return url;
    }

    public boolean isRedirect() {
        return isRedirect;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public void setRedirect(boolean redirect) {
        isRedirect = redirect;
    }
}
